package com.zy.swagger.service.sys.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.zy.swagger.annotation.LogCostTime;
import com.zy.swagger.base.BaseDao;
import com.zy.swagger.base.BaseServiceImpl;
import com.zy.swagger.converter.SysUserConverter;
import com.zy.swagger.dao.SysRoleDao;
import com.zy.swagger.dao.SysUserDao;
import com.zy.swagger.dto.CommonIdDTO;
import com.zy.swagger.dto.ModifyPwdDTO;
import com.zy.swagger.dto.SysUserDTO;
import com.zy.swagger.entity.sys.SysUser;
import com.zy.swagger.service.sys.SysUserService;
import com.zy.swagger.util.LoginUserUtil;
import com.zy.swagger.util.PageHelperTool;
import com.zy.swagger.vo.SysUserVO;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 系统用户表(表sys_user)服务接口实现类
 *
 * @author ZY
 * @date 2021-04-24 00:08:46
 */
//@DubboService(interfaceClass = SysUserService.class)
@Service("sysUserService")
public class SysUserServiceImpl extends BaseServiceImpl<SysUser, Integer, Object> implements SysUserService {

    /**
     * 注入持久层对象
     */
    @Resource
    private SysUserDao dao;

    @Resource
    private SysRoleDao sysRoleDao;

    /**
     * 定义抽象方法getDao获取当前实体Mapper对象
     *
     * @return 当前实体Mapper对象
     */
    @Override
    protected BaseDao<SysUser> getDao() {
        return this.dao;
    }

    /**
     * 新增数据
     *
     * @param dto 参数对象
     * @return 视图对象
     */
    @Override
    public SysUserVO insert(SysUserDTO dto) throws Exception {
        SysUser entity = SysUserConverter.convertFromDTO(dto);
        entity.setCreateTime(new Date());
        SysUser res = super.insertSelective(entity);
        if (res != null) {
            return SysUserConverter.convertToVO(res);
        }
        return null;
    }

    /**
     * 删除对象
     *
     * @param dto 参数对象
     * @return true:删除成功 false:删除失败
     */
    @Override
    public Integer delete(CommonIdDTO dto) {
        return super.deleteByPrimaryKey(Integer.parseInt(dto.getId()));
    }

    /**
     * 更新对象
     *
     * @param dto 待更新的DTO对象
     * @return 成功返回更新后的VO对象，失败返回null
     */
    @Override
    public SysUserVO update(SysUserDTO dto) {
        SysUser entity = SysUserConverter.convertFromDTO(dto);
        entity.setUpdateTime(new Date());
        int res = super.updateByPrimaryKeySelective(entity);
        if (res == 1) {
            return SysUserConverter.convertToVO(entity);
        }
        return null;
    }

    /**
     * 根据ID查询数据
     *
     * @param dto 主键DTO对象
     * @return 成功返回对应ID的VO对象，失败返回null
     */
    @LogCostTime
    @Override
    public SysUserVO getById(CommonIdDTO dto) {
        SysUser entity = super.getByPrimaryKey(Integer.parseInt(dto.getId()));
        if (entity != null) {
            return SysUserConverter.convertToVO(entity);
        }
        return null;
    }

    /**
     * 根据条件查询数据集合
     *
     * @param dto 查询条件对象
     * @return 满足条件的数据集合
     */
    @Override
    public List<SysUserVO> getList(SysUserDTO dto) {
        Example example = new Example(SysUser.class);
        // TODO 根据自身业务情况组装查询条件查询列表(下面是示例)
        //Example.Criteria criteria = example.createCriteria();
        //criteria.andEqualTo("id", dto.getId());
        //criteria.andGreaterThanOrEqualTo("createTime", dto.getCreateTimeBegin());
        //criteria.andLessThanOrEqualTo("createTime", dto.getCreateTimeEnd());
        List<SysUser> list = super.selectByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            List<SysUserVO> retList = new ArrayList<>();
            list.forEach(x -> retList.add(SysUserConverter.convertToVO(x)));
            return retList;
        }
        return new ArrayList<>();
    }

    /**
     * 根据条件查询分页
     *
     * @param dto 查询条件
     * @return 满足条件的分页
     */
    @Override
    public PageInfo<SysUserVO> getPageInfo(SysUserDTO dto) {
        Integer pageNum = dto.getPageNum();
        Integer pageSize = dto.getPageSize();

        Example example = new Example(SysUser.class);
        // TODO 根据自身业务情况组装查询条件查询分页(下面是示例)
        //Example.Criteria criteria = example.createCriteria();
        //criteria.andEqualTo("id", dto.getId());
        //criteria.andGreaterThanOrEqualTo("createTime", dto.getCreateTimeBegin());
        //criteria.andLessThanOrEqualTo("createTime", dto.getCreateTimeEnd());
        PageInfo<SysUser> pageInfo = PageHelper.startPage(pageNum, pageSize).setOrderBy("id desc").doSelectPageInfo(() -> super.selectByExample(example));
        if (pageInfo == null || CollectionUtils.isEmpty(pageInfo.getList())) {
            return PageHelperTool.initPageInfoObj(pageNum, 0, pageSize, new PageInfo<>(Lists.newArrayList()));
        }
        List<SysUserVO> retList = new ArrayList<>();
        pageInfo.getList().forEach(x -> retList.add(SysUserConverter.convertToVO(x)));
        return PageHelperTool.initPageInfoObj(pageNum, (int) pageInfo.getTotal(), pageSize, new PageInfo<>(retList));
    }

    /**
     * 修改密码
     *
     * @param dto 修改密码参数
     * @return 返回1:成功 0:失败
     */
    @Override
    public Integer modifyPwd(ModifyPwdDTO dto) {
        Integer currentUserId = LoginUserUtil.getCurrentUserId();
        String oldPwd = dto.getOldPwd();
        String newPwd = dto.getNewPwd();
        SysUser sysUser = super.getByPrimaryKey(currentUserId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (sysUser != null && encoder.matches(oldPwd, sysUser.getPassword())) {
            sysUser.setPassword(encoder.encode(newPwd));
            super.updateByPrimaryKeySelective(sysUser);
            return 1;
        }
        return 0;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = this.dao.getUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在!");
        }
        user.setRoles(sysRoleDao.getRolesByUserId(user.getId()));
        return user;
    }
}